package com.foreveross.common;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;

public class PropertiesManagerParam {
	
	private static PropertiesManagerParam propertiesManagerParam;
	
	private PropertiesManagerParam(){};
	
	public static PropertiesManagerParam getInstance(){
		if(propertiesManagerParam == null) return new PropertiesManagerParam();
		else return propertiesManagerParam;
	}
	
	public void readProperties(String path,Class clazz){
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path),"utf-8");
			Properties properties = new Properties();
			properties.load(inputStreamReader);
			
			for(Map.Entry<Object, Object> entry :properties.entrySet()){
				Field field = clazz.getDeclaredField((String)entry.getKey());
				Class fieldType = field.getType();
				boolean isTurn = true;
				while(isTurn){
					try{
						isTurn = false;
						if(fieldType.equals(int.class)){
							field.setInt(clazz, Integer.parseInt((String)entry.getValue()));
						}else if(fieldType.equals(float.class)){
							field.setFloat(clazz, (Float) entry.getValue());
						}else if(fieldType.equals(Boolean.class)){
							field.setBoolean(clazz, (Boolean) entry.getValue());
						}else if(fieldType.equals(double.class)){
							field.setDouble(clazz, (Double) entry.getValue());
						}else if(fieldType.equals(String.class)){
							field.set(clazz, entry.getValue());
						}else{
							field.set(clazz, entry.getValue());
						}
					}catch(Exception e){
						field.setAccessible(true);
						isTurn = false;
					}
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) {
		PropertiesManagerParam p = new PropertiesManagerParam();
		String path = "E:\\workspace\\pushModule\\WebRoot\\WEB-INF\\constants.properties";
		p.readProperties(path,Constants.class);
	}
}
